package com.beifu.manager.service.assetscrap.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.beifu.manager.api.domain.scrap.ScrapDetailResponse;
import com.beifu.manager.api.domain.scrap.ScrapListResponse;
import com.beifu.manager.api.domain.scrap.ScrapProduct;
import com.beifu.manager.dao.AssetInfoMapper;
import com.beifu.manager.dao.AssetScrapDetailMapper;
import com.beifu.manager.dao.AssetScrapMapper;
import com.beifu.manager.dao.ImgMapper;
import com.beifu.manager.dao.TrainInfoMapper;
import com.beifu.manager.dao.UserInfoMapper;
import com.beifu.manager.model.AssetInfo;
import com.beifu.manager.model.AssetInfoExample;
import com.beifu.manager.model.AssetScrap;
import com.beifu.manager.model.AssetScrapDetail;
import com.beifu.manager.model.AssetScrapDetailExample;
import com.beifu.manager.model.AssetScrapDetailExample.Criteria;
import com.beifu.manager.model.AssetScrapExample;
import com.beifu.manager.model.Img;
import com.beifu.manager.model.TrainInfo;
import com.beifu.manager.model.UserInfo;
import com.beifu.manager.service.assetscrap.AssetScrapService;
import com.beifu.manager.service.assetscrapdetail.AssetScrapDetailService;
import com.beifu.manager.shiro.ActiveUser;
import com.mds.manager.utils.PageUtils;
import com.utils.Constants.ASSET_INFO_STATUS;
@Service
public class AssetScrapServiceImpl implements AssetScrapService {
	private Logger Log = Logger.getLogger(this.getClass());
	
	@Autowired
	private AssetScrapMapper assetScrapMapper;
	@Autowired
	private AssetScrapDetailMapper assetScrapDetailMapper;
	@Autowired
	private UserInfoMapper userInfoMapper;
	@Autowired
	private TrainInfoMapper trainInfoMapper;
	@Autowired
	private AssetInfoMapper assetInfoMapper;
	@Autowired
	private AssetScrapDetailService assetScrapDetailService;
	@Autowired
	private ImgMapper imgMapper;
	
	@Override
	public PageUtils getAssetScrapList(PageUtils page) {
		AssetScrapExample example = (AssetScrapExample) page.getQueryParames();
		
		List<AssetScrap> list = assetScrapMapper.getAssetScrapPage((page.getPage()-1)*page.getLimit(),page.getLimit(), example);
		for (AssetScrap assetScrap : list) {
			UserInfo userInfo = userInfoMapper.selectByPrimaryKey(assetScrap.getCreateUserId());
			TrainInfo trainInfo = null;
			if(null != userInfo){
				assetScrap.setCreateUserName(userInfo.getUserName());
				trainInfo = trainInfoMapper.selectByPrimaryKey(userInfo.getOrganizeId());
			}
			if(null != trainInfo){
				assetScrap.setTrainNumber(trainInfo.getTrainNumber());
			}
			
		}
		int count = assetScrapMapper.countByExample(example);
		
		page.setList(list);
		page.setCountNum(count);
		return page;
	}
	
	@Override
	public AssetScrap getAssetScrapDetail(String id) {
		if(StringUtils.isEmpty(id)){
			return null;
		}
		AssetScrap assetScrap = assetScrapMapper.selectByPrimaryKey(Integer.parseInt(id));
		UserInfo createUser = userInfoMapper.selectByPrimaryKey(assetScrap.getCreateUserId());//获取创建人信息
		UserInfo approveUser = userInfoMapper.selectByPrimaryKey(assetScrap.getApproveId());//获取审批人信息
		if(null != createUser){
			assetScrap.setCreateUserName(createUser.getUserName());
		}
		if(null != approveUser){
			assetScrap.setApproveName(approveUser.getUserName());
		}
		//转换创建时间
		Date createTime = assetScrap.getCreateTime();
		if(null != createTime){
			String createTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(createTime);
			assetScrap.setCreateTimeStr(createTimeStr);
		}
		//转换审批时间
		Date approveDate = assetScrap.getApproveDate();
		if(null != approveDate){
			String approveDateStr = new SimpleDateFormat("yyyy-MM-dd").format(approveDate);
			assetScrap.setApproveDateStr(approveDateStr);
		}
		//转换完成时间
		Date completeTime = assetScrap.getCompleteTime();
		if(null != completeTime){
			String comTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(completeTime);
			assetScrap.setComTimeStr(comTimeStr);
		}
		
		//获取类型、数量、确认数量:类型id,类型名称name,类型数量num,确认数量confirmNum
		List<Map<String, Object>> typeList = assetScrapMapper.getAssetTypeNum(assetScrap.getId());
		assetScrap.setTypeList(typeList);
		
		//获取报废图片
		String photoIds = assetScrap.getPhoto();
		
		List<String> imgs = getImgs(photoIds);
		
		assetScrap.setImgList(imgs);
		return assetScrap;
	}
	
	/**
	 * 更据订单id获取照片
	 * @param images
	 * @return
	 */
	private List<String> getImgs(String images) {
		List<String> imgList = new ArrayList<String>();
		
		if(StringUtils.isNotEmpty(images)){
			String[] imgIds = images.split(",");
			for (String imgId : imgIds) {
				Img img = imgMapper.selectByPrimaryKey(Long.parseLong(imgId));
				if(null != img){
					imgList.add(new String(img.getImgbase64()));
				}
			}
		}
		
		return imgList;
	}
	
	@Override
	public Map<String, Object> approveAssetsScrap(String id) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isEmpty(id)){
			Log.info("========未获取到报废订单id======");
			map.put("code", "error");
			map.put("msg", "报废审核通过失败");
			return map;
		}
		
		int assetId = Integer.parseInt(id);
		
		//查看报废订单的状态，如果已审核结束流程
		AssetScrap scrap = assetScrapMapper.selectByPrimaryKey(assetId);
		if(null == scrap){
			Log.info("========未获取到报废订单======");
			map.put("code", "error");
			map.put("msg", "报废审核通过失败");
			return map;
		}else {
			if(StringUtils.equals("1", scrap.getStatus()) ||
					StringUtils.equals("2", scrap.getStatus())){
				Log.info("========该报废订单id已审核 ======");
				map.put("code", "error");
				map.put("msg", "该订单已审核");
				return map;
			}
		}
		
		Log.info("========更新报废订单状态======");
		
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
		String userId = activeUser.getUserId();
		//1、确认审核通过，更新报废订单状态为1：报废
		AssetScrap assetScrap = new AssetScrap();
		assetScrap.setId(assetId);
		assetScrap.setStatus("1");//报废订单状态为1：报废
		assetScrap.setApproveId(Integer.parseInt(userId));//审批人Id
		assetScrap.setCompleteTime(new Date());
		assetScrap.setApproveDate(new Date());//审批时间
		assetScrapMapper.updateByPrimaryKeySelective(assetScrap);
		
		Log.info("========更新资产信息状态======");
		
		//2、更新资产信息表为报废
		//根据订单id和状态为1：待报废 的获取资产RFID
		AssetScrapDetailExample example = new AssetScrapDetailExample();
		Criteria criteria = example.createCriteria();
		criteria.andAssetScrapIdEqualTo(assetId).andScrapStatusEqualTo(1);
		
		AssetScrapDetail detail = new AssetScrapDetail();
		detail.setScrapTime(new Date());
		assetScrapDetailMapper.updateByExampleSelective(detail, example);
		
		List<AssetScrapDetail> list = assetScrapDetailMapper.selectByExample(example);
		for (AssetScrapDetail assetScrapDetail : list) {
			String rfidCode = assetScrapDetail.getAssetInfoRfidCode();
			
			AssetInfo info = new AssetInfo();
			info.setIsScrap("1");//是否报废：1报废
			info.setStatus(Integer.valueOf(ASSET_INFO_STATUS.Scrap.getStatus()));//报废
			AssetInfoExample infoExample = new AssetInfoExample();
			infoExample.createCriteria().andRfidCodeEqualTo(rfidCode);
			
			assetInfoMapper.updateByExampleSelective(info, infoExample);
		}
		
		map.put("code", "success");
		map.put("msg", "报废审核通过成功！");
		return map;
	}

	@Override
	public PageUtils getScrapDetailTable(PageUtils page) {
		AssetScrapDetailExample example = (AssetScrapDetailExample) page.getQueryParames();
		
		List<AssetScrapDetail> list = assetScrapDetailMapper.selectScrapDetailPage((page.getPage()-1)*page.getLimit(),page.getLimit(), example);
		for (AssetScrapDetail assetScrapDetail : list) {
			//获取资产类型名称
			String rfidCode = assetScrapDetail.getAssetInfoRfidCode();
			Map<String, Object> assetType = assetScrapDetailMapper.getTypeName(rfidCode);//获取资产名称和自定义编号
			if(null != assetType){
				assetScrapDetail.setTypeName((String) assetType.get("typeName"));
			}

			//转换报废时间格式
			Date scrapTime = assetScrapDetail.getScrapTime();
			if(null != scrapTime){
				String scrapTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(scrapTime);
				assetScrapDetail.setScrapTimeStr(scrapTimeStr);
			}
		}
		int count = assetScrapDetailMapper.countByExample(example);
		page.setList(list);
		page.setCountNum(count);
		return page;
	}

	@Override
	public Map<String, Object> refuseAssetsScrap(String id, String refuseReason) {
		Map<String, Object> map = new HashMap<String, Object>();
		if(StringUtils.isEmpty(id)){
			Log.info("========未获取到报废订单id======");
			map.put("code", "error");
			map.put("msg", "驳回报废失败");
			return map;
		}
		
		int assetId = Integer.parseInt(id);
		
		//查看报废订单的状态，如果已审核结束流程
		AssetScrap scrap = assetScrapMapper.selectByPrimaryKey(assetId);
		if(null == scrap){
			Log.info("========未获取到报废订单======");
			map.put("code", "error");
			map.put("msg", "驳回报废失败");
			return map;
		}else {
			if(StringUtils.equals("1", scrap.getStatus()) ||
					StringUtils.equals("2", scrap.getStatus())){
				Log.info("========该报废订单id已审核 ======");
				map.put("code", "error");
				map.put("msg", "该订单已审核");
				return map;
			}
		}
		
		Log.info("========更新报废订单状态======");
		
		Subject subject = SecurityUtils.getSubject();
		ActiveUser activeUser = (ActiveUser)subject.getPrincipal();
		String userId = activeUser.getUserId();
		//1、报废单驳回，更新报废订单状态为1：报废;2:驳回
		AssetScrap assetScrap = new AssetScrap();
		assetScrap.setId(assetId);
		assetScrap.setStatus("2");//报废订单状态为2:驳回
		assetScrap.setRefuseReason(refuseReason);
		assetScrap.setApproveId(Integer.parseInt(userId));//审批人Id
		assetScrap.setCompleteTime(new Date());
		assetScrap.setApproveDate(new Date());//审批时间
		assetScrapMapper.updateByPrimaryKeySelective(assetScrap);
		
		map.put("code", "success");
		map.put("msg", "驳回报废成功！");
		return map;
	}

	@Override
	public List<ScrapListResponse> getScrapList(String pageIndex, String pageNumber,String userId) {
		
		List<ScrapListResponse> list = new ArrayList<ScrapListResponse>();//返回前端展示的
		
		if(StringUtils.isEmpty(pageIndex) && StringUtils.isEmpty(pageNumber)){
			Log.info("+++++++++传入的分页参数为空+++++++++++");
			pageIndex = "1";
			pageNumber = "10";
		}
		int pageCur = Integer.parseInt(pageIndex);//当前页数
		int pageSize = Integer.parseInt(pageNumber);//每页显示的条数
		
		AssetScrapExample example = new AssetScrapExample();
		UserInfo user = userInfoMapper.selectByPrimaryKey(Integer.decode(userId));
		if (user!=null ) {
			if (!user.getOrganize().getOrganizeType().equals(1)) {
				example.createCriteria().andCreateUserIdEqualTo(Integer.valueOf(userId));
			}
		}
		List<AssetScrap> assetScrapList = assetScrapMapper.getAssetScrapPage((pageCur-1)*pageSize, pageSize, example);
		if (null != assetScrapList && assetScrapList.size() > 0) {
			for (AssetScrap assetScrap : assetScrapList) {
				ScrapListResponse res = new ScrapListResponse();
				res.setScrapId(assetScrap.getId().toString());
				res.setStatus(assetScrap.getStatus());
				
				list.add(res);
			} 
		}
		return list;
	}

	@Override
	public ScrapDetailResponse getScrapDetail(String id) {
		ScrapDetailResponse res = new ScrapDetailResponse();
		if(StringUtils.isEmpty(id)){
			return null;
		}
		int assetScrapId = Integer.parseInt(id);
		AssetScrap assetScrap = assetScrapMapper.selectByPrimaryKey(assetScrapId);
		if(null != assetScrap){

			UserInfo createUser = userInfoMapper.selectByPrimaryKey(assetScrap.getCreateUserId());//获取创建人信息
			UserInfo approveUser = userInfoMapper.selectByPrimaryKey(assetScrap.getApproveId());//获取审批人信息
			if(null != createUser){
				res.setApplyName(createUser.getUserName());//申请人
			}
			if(null != approveUser){
				res.setApprovalName(approveUser.getUserName());//审批人
			}
			//转换创建时间
			Date createTime = assetScrap.getCreateTime();
			if(null != createTime){
				String createTimeStr = new SimpleDateFormat("yyyy-MM-dd").format(createTime);
				res.setApplyDate(createTimeStr);
			}
			//转换审批时间
			Date approveDate = assetScrap.getApproveDate();
			if(null != approveDate){
				String approveDateStr = new SimpleDateFormat("yyyy-MM-dd").format(approveDate);
				res.setApprovalDate(approveDateStr);
			}
			
//			res.setPhoto(assetScrap.getPhoto().toString());
			res.setRemark(assetScrap.getRemark());
			res.setTrainTime(assetScrap.getTrainNumber());
			res.setRefuseReason(assetScrap.getRefuseReason());
			//获取该报废单资产报废列表
			List<ScrapProduct> prodList = assetScrapDetailService.getAssetScrapDetail(assetScrapId, assetScrap.getStatus());
			res.setScrapList(prodList);
			//报废数量
			String scrapNum = "0";
			// status：1 报废;2 驳回;0 未处理
			if(StringUtils.equals("1", assetScrap.getStatus())){
				scrapNum = assetScrapDetailService.getScrapNum(assetScrapId, assetScrap.getStatus());
			}else if (StringUtils.equals("0", assetScrap.getStatus())){
				scrapNum = prodList.size()+"";
			}
			res.setScrapNum(scrapNum);
			
			//获取报废照片
			String photoIds = assetScrap.getPhoto();
			List<String> imgs = getImgs(photoIds);
			
			res.setImgs(imgs);
			
		}
		return res;
	}

	@Override
	public void saveAssetScrap(AssetScrap assetScrap, List<ScrapProduct> scrapList, String devID) {
		List<String> imgList = assetScrap.getImgList();
		String ids = "";
		if(null != imgList && imgList.size() > 0){
			for (String imgBase64 : imgList) {
				Img img = new Img();
				img.setImgbase64(imgBase64.getBytes());
				imgMapper.insertAndGetId(img);//将图片放入图片表中并返回主键
				
				ids += img.getId() + ",";
			}
			ids = ids.substring(0, ids.length()-1);
		}
		
		assetScrap.setPhoto(ids);
		
		UserInfo userInfo = userInfoMapper.selectByPrimaryKey(assetScrap.getCreateUserId());
		if(null != userInfo){
			assetScrap.setSrcOrganizeId(userInfo.getOrganizeId());//所属组织id
		}
		//将报废单数据保存到asset_scrap同时返回主键
		assetScrapMapper.insertSelective(assetScrap);
		Integer id = assetScrap.getId();
		//保存报废单详情
		if(null != scrapList && scrapList.size() > 0){
			for (ScrapProduct scrapProduct : scrapList) {
				AssetScrapDetail assetScrapDetail = new AssetScrapDetail();
				assetScrapDetail.setAssetInfoRfidCode(scrapProduct.getRFID());
				assetScrapDetail.setAssetScrapId(id);
				assetScrapDetail.setScrapStatus(0);//初始化未处理
				assetScrapDetail.setOperatingUserId(assetScrap.getCreateUserId());
				assetScrapDetail.setOperatingDeviceId(devID);
				assetScrapDetailMapper.insertSelective(assetScrapDetail);
			}
		}
		
	}

	@Override
	public void saveAssetScrap(String scrapId, List<ScrapProduct> scrapList) {
		// TODO Auto-generated method stub
		
		if(null != scrapList && scrapList.size() > 0){
			for (ScrapProduct scrapProduct : scrapList) {
				AssetScrapDetail detail = new AssetScrapDetail();
				detail.setScrapStatus(1);//由0未处理，更新为1待报废
				
				String rfId = scrapProduct.getRFID();
				AssetScrapDetailExample example = new AssetScrapDetailExample();
				example.createCriteria().andAssetInfoRfidCodeEqualTo(rfId)
										.andAssetScrapIdEqualTo(Integer.parseInt(scrapId));
				
				assetScrapDetailMapper.updateByExampleSelective(detail, example);
				
			}
		}
	}

	@Override
	public List<AssetScrapDetail> getAssetScrapRFIDs(String scrapId) {

		AssetScrapDetailExample example = new AssetScrapDetailExample();
		example.createCriteria().andAssetScrapIdEqualTo(Integer.valueOf(scrapId));
		List<AssetScrapDetail> assetScrapDetails = assetScrapDetailMapper.selectByExample(example);
		return assetScrapDetails;
	}

}
